﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.LinqToSqlProvider;
using MvcEngine.Gallery.Repositories;
using MvcEngine.Gallery.Models;

namespace MvcEngine.Gallery.LinqToSqlProvider
{
    public class GalleryRepository : Repository, IGalleryRepository
    {
        public GalleryData Get(Guid id)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Galleries().SingleOrDefault(t => t.Id == id);
            }
        }

        public IList<GalleryData> GetAll(Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return (from b in contextManager.Context.Galleries()
                        join
                        p in contextManager.Context.Pages() on b.PageId equals p.Id
                        where p.SiteId == siteId
                        select b).ToList();
            }
        }

        public void Add(GalleryData gallery)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Galleries().InsertOnSubmit(gallery);
                contextManager.Commit();
            }
        }

        public void Update(GalleryData gallery)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Commit();
            }
        }

        public void Delete(Guid id)
        {
            throw new NotImplementedException();
        }

        public GalleryData GetByPage(Guid pageId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Galleries().SingleOrDefault(t => t.PageId == pageId);
            }
        }

        public GalleryData Get(string galleryName)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Galleries().SingleOrDefault(t => t.Name == galleryName);
            }
        }
    }
}
